/*
 * Copyright 2002-2016 the Beijing Brain Technology co.,LTD http://www.bris.cn/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bris.niosocket.nioserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import com.bris.niosocket.Server;
import com.bris.niosocket.handler.DispatcherHandler;
import com.bris.niosocket.handler.codec.RequestDecoder;
import com.bris.niosocket.handler.codec.ResponseEncoder;

/**
 * 基于Netty的NIO Socket Server</br>
 * 2016年2月2日</br>
 * @author xunaidong
 * @since 1.0.0
 */
public class NettyServer implements Server {
	
	private EventLoopGroup bossGroup;
	private EventLoopGroup workGroup;
	ChannelFuture future;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.bris.niosocket.Server#stop()
	 */
	@Override
	public void stop() {
		bossGroup.shutdownGracefully();
		workGroup.shutdownGracefully();

	}
	
	private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{

		/* (non-Javadoc)
		 * @see io.netty.channel.ChannelInitializer#initChannel(io.netty.channel.Channel)
		 */
		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ch.pipeline().addLast(new RequestDecoder()).addLast(new ResponseEncoder()).addLast(new DispatcherHandler());
			
		}
		
	}

	/* (non-Javadoc)
	 * @see com.bris.niosocket.Server#start()
	 */
	@Override
	public void start() {
		bossGroup = new NioEventLoopGroup();
		workGroup = new NioEventLoopGroup();
		try {
		ServerBootstrap server = new ServerBootstrap();
		server.group(bossGroup, workGroup)
				.channel(NioServerSocketChannel.class)
				.option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.SO_REUSEADDR, true).childHandler(new ChildChannelHandler());
		future = server.bind(8080).sync();
		future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.exit(1);
		}finally{
			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
		
	}

}
